package com.niudong.esdemo.service.impl;

import com.niudong.esdemo.service.RankEvalService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.rankeval.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RankEvalServiceImpl2 implements RankEvalService {

    private static Log log = LogFactory.getLog(RankEvalServiceImpl.class);

    private RestHighLevelClient restClient;

    // 初始化连接
    @PostConstruct
    public void initEs() {
        restClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));

        log.info("ElasticSearch init in service.");
    }

    // 关闭连接
    public void closeEs() {
        try {
            restClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public RankEvalRequest buildRankEvalRequest(String index,String documentId,String field,String content){
        PrecisionAtK metric = new PrecisionAtK();

        List<RatedDocument> ratedDocs = new ArrayList<>();
        ratedDocs.add(new RatedDocument(index,documentId,1));

        SearchSourceBuilder searchQuery = new SearchSourceBuilder();

        searchQuery.query(QueryBuilders.matchQuery(field,content));
        // 将前三个部分合并为RatedRequest
        RatedRequest ratedRequest = new RatedRequest("content_query", ratedDocs, searchQuery);
        List<RatedRequest> ratedRequests = Arrays.asList(ratedRequest);

        // 创建排名评估规范
        RankEvalSpec specification = new RankEvalSpec(ratedRequests, metric);
        // 创建排名评估请求
        RankEvalRequest request = new RankEvalRequest(specification, new String[] {index});

        return request;
    }




    @Override
    public void executeRankEvalRequest(String index, String documentId, String field, String content) {

    }
}
